$(function () {


    $("#examineBuyer").attr("class", "active");

    //加载表格
    initDataGrid();


    $('#queryDate').daterangepicker(
        {
            opens: 'left',
            format: 'yyyy-MM-dd',
            separator: '至',
            startDate: Date.today().add({days: -29}),
            endDate: Date.today(),
            locale: {
                fromLabel: 'From',
                toLabel: 'to',
                daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                firstDay: 1
            },
            showWeekNumbers: true,
        },
        function (start, end) {
            $('#queryDate span').html(start.toString('yyyy-MM-dd') + ' - ' + end.toString('yyyy-MM-dd'));
        }
    );

})


function initDataGrid() {
    //创建bootstrapTable
    $("#dataGrid").bootstrapTable('destroy').bootstrapTable({
        method: "GET",
        dataType: "json",
        url: '../admin/getBuyerExaminationList',
        pagination: true,//显示分页条：页码，条数等
        striped: true,//隔行变色
        pageNumber: 1,//首页页码
        pageSize: 10,//分页，页面数据条数
        pageList: [5, 10, 15, 20],
        queryParamsType: "",
        queryParams: function (params) {
            var createDate = $("#queryDate").val();
            var startDate = createDate.substr(0, createDate.indexOf('至'));
            var endDate = createDate.substr(createDate.indexOf('至') + 1, createDate.length);

            var status = $("#queryStatus").val();
            var name = $("#queryName").val();
            var phone = $("#queryPhone").val();

            return {
                // 说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值
                pageSize: params.pageSize,
                pageNum: params.pageNumber,
                phone: phone,
                name: name,
                status: status,
                startTime: startDate,
                endTime: endDate
            };
        },
        uniqueId: "id",//Indicate an unique identifier for each row
        sidePagination: "server",//在服务器分页
        sortName: "id",
        toolbar: "#toolbar",//工具栏
        columns: [{
            checkbox: "true",
            field: "box"
        }, {
            title: "ID",
            field: "id",
            visible: false,
            sortable: true
        }, {
            title: "买手名称",
            field: "name",
            width: "100px"
        }, {
            title: "手机号码",
            field: "phone"
        }, {
            title: "状态",
            field: "status",
            formatter: function (value, row, index) {
                if (value == 1) {
                    return "待审核";
                } else if (value == 2) {
                    return "已审核";
                } else if (value == 3) {
                    return "已驳回";
                }
            }
        }, {
            title: "上传时间",
            field: "createTime",
            formatter: function (value, row, index) {
                return changeDateFormat(value)
            }
        }, {
            title: "审核时间",
            field: "auditTime",
            formatter: function (value, row, index) {
                return changeDateFormat(value)
            }
        }, {
            title: "操作",
            width: "200px",
            formatter: function (value, row, index) {
                var buyeId = row.id;
                return '<input type="button" value="查看详情" data-toggle="modal" data-target="#infoModal"  class="btn btn-primary" onclick="getBuyerInfo('+buyeId+')"/>'
            }
        }],
        // showRefresh: true
//            showExport:true
    });
}

function query() {
    initDataGrid();
}

function getBuyerInfo(id) {
    $("#pic").empty()
    $("#business").empty()
    $("#status").empty()
    $.ajax({
        url: "../admin/getBuyerInfo/" + id,
        type: "get",
        dataType: "json",
        async: false,
        success: function (data) {
            var store = data.data;
            $("#buyerId").val(store.id)
            $("#name").text(store.name)
            $("#mobile").text(store.mobile)
            $("#email").text(store.email)
            $("#company").text(store.company)
            $("#introduction").html(store.introduction)
            $("#price").text(store.priceDownLimit+"-"+store.priceUpperLimit)
            $("#business").append(' <img src="'+store.businessLicense+'" width="100%" height="100px">')

            var picList = eval(store.pictureUrls);
            for (var i = 0; i < picList.length; i++) {
                $("#pic").append(' <img src="'+picList[i]+'" width="100px" height="100px">')
            }
            var status = store.status;
            if (status == 1){
                $("#status").append('<input type="button" value="同意" class="btn btn-primary" onclick="auditBuyer(2)" style="float: left"/>\n' +
                    '<input type="button" value="驳回" class="btn btn-danger" onclick="auditBuyer(3)" style="float: left"/>')
            }else if(status == 2){
                $("#status").append('<input type="button" value="驳回" class="btn btn-danger" onclick="auditBuyer(3)" style="float: left"/>')
            }else if(status == 3){
                $("#status").append('<input type="button" value="同意" class="btn btn-primary" onclick="auditBuyer(2)" style="float: left"/>')
            }


        },
        error: function (data) {
        }
    });
}

function auditBuyer(status) {
     $.ajax({
         url: "../admin/examineBuyer",
         type: "post",
         data:{
             "buyerId":$("#buyerId").val(),
             "status":status
         },
         dataType: "json",
         async: false,
         success: function (data) {
            $("#infoModal").modal('hide')
             $("#pic").empty()
             $("#business").empty()
             $("#status").empty()

             $("#dataGrid").bootstrapTable("refresh");
         },
         error: function (data) {
         }
     });
}

$("#batchAgreeBuyer").click(function(){
    batchExamineBuyer(2);
})

$("#batchRejectBuyer").click(function(){
    batchExamineBuyer(3);
})



function batchExamineBuyer (status){
    var rows = $("#dataGrid").bootstrapTable("getSelections");
    var ids = [];
    var len = rows.length;
    if (len == 0) {
        alert("请选择一行或者多行记录！");
        return
    }
    for (var i = 0; i < len; i++) {
        ids.push(rows[i].id);
    }
    $.ajax({
        url: "../admin/batchExamineBuyer",
        type: "post",
        dataType: "json",
        data: {
            "ids": ids,
            "status":status
        },
        success: function (data) {
            $("#dataGrid").bootstrapTable("refresh");
        },
        error: function () {
        }
    });
}


//转换日期格式(时间戳转换为datetime格式)
function changeDateFormat(cellval) {
    var dateVal = cellval + "";
    if (cellval != null) {
        var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
    }
}








